<?php

namespace app\merchant\controller;

use app\common\model\WithdrawModel;
use app\common\model\Merchant;
use think\Request;
use think\Db;

class Withdraw extends Common
{

    public $model;
    public $merchant;

    public function __construct(Request $request,WithdrawModel $model,Merchant $merchant)
    {
        parent::__construct($request);
        $this->model = $model;
        $this->merchant = $merchant;
    }

    public function index()
    {
        $user = $this->merchant->getById(session('merchant.merchant_id'));
        if(!$user){
            return returnJson('300', '用户不存在', '');
        }

        $data = $this->model->getByMerchantId(session('merchant.merchant_id'));

        return view('recond',['data' => $data]);
    }

    public function withdrawals(){
        $user = $this->merchant->getById(session('merchant.merchant_id'));
        if(!$user){
            return returnJson('300', '用户不存在', '');
        }
        //查询每日已经提现的金额
        $dailyWithdrawalAmount = $this->model->getDailyWithdrawalAmount();
        if($dailyWithdrawalAmount >= 50000 ){
            return returnJson('300', '今日提现金额超出限制额度，你还可提取0元', '');
        }
        $withdrawMoney = floatval(input('post.withdraw_money'));
        if($withdrawMoney > 50000 - $dailyWithdrawalAmount){
            return returnJson('300', '今日提现金额超出限制额度,你还可提取'.(50000 - $dailyWithdrawalAmount).'元', '');
        }
        if($withdrawMoney < 1){
            return returnJson('300', '至少取1元', '');
        }
        if(floatval($user['merchant_coin']) < $withdrawMoney){
            return returnJson('300', '账户余额不足', '');
        }
        $merchantBalance = $user['merchant_coin'] - $withdrawMoney; //账户余额
        $ret = $this->model->create([
            'merchant_id' => session('merchant.merchant_id'),
            'create_time'        => time(),
            'withdraw_money'       => $withdrawMoney,
            'merchant_balance'     => $merchantBalance,
            'withdraw_status'      => '1',
        ]);
        if(!$ret){
            return returnJson('300', '提现失败！请跟客服联系', '');
        }
        $this->merchant->updateById(session('merchant.merchant_id'),[
            'merchant_coin' => $merchantBalance
        ]);
        return returnJson('200', '提现成功', '');
    }
}
